<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ContractsForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="客户" v-bind="validateInfos.customerName" id="ContractsForm-customerName" name="customerName">
                <a-input v-model:value="formModel.customerName" placeholder="请输入客户" :allow-clear ="!disabled" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="合同主题" v-bind="validateInfos.contractTheme" id="ContractsForm-contractTheme" name="contractTheme">
                <a-input v-model:value="formModel.contractTheme" placeholder="请输入合同主题" :allow-clear="!disabled"  />
              </a-form-item>
            </a-col>
            <!-- 隐藏客户编号字段 -->
            <!-- <a-col :span="24">
              <a-form-item label="客户编号" v-bind="validateInfos.customerId" id="ContractsForm-customerId" name="customerId">
                <a-input v-model:value="formModel.customerId" placeholder="请输入客户编号" :allow-clear ="!disabled" />
              </a-form-item>
            </a-col> -->
            <a-col :span="24">
              <a-form-item label="产品类型" v-bind="validateInfos.productType" id="ContractsForm-productType" name="productType">
                <a-select
                  v-model:value="formModel.productType"
                  placeholder="请选择产品类型"
                  :allow-clear="!disabled"
                  @change="handleProductTypeChange"
                  :loading="productTypeLoading"
                  :disabled="disabled"
                >
                  <a-select-option
                    v-for="item in productTypeOptions"
                    :key="item.id"
                    :value="item.productTypeName || item.productType || item.name"
                  >
                    {{ item.productTypeName || item.productType || item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="产品内容" v-bind="validateInfos.productContent" id="ContractsForm-productContent" name="productContent">
                <a-select
                  v-model:value="formModel.productContent"
                  placeholder="请选择产品内容"
                  :allow-clear="!disabled"
                  :disabled="disabled || !formModel.productType"
                  :loading="productContentLoading"
                >
                  <a-select-option
                    v-for="item in productContentOptions"
                    :key="item.id"
                    :value="item.productName || item.name"
                  >
                    {{ item.productName || item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="币种" v-bind="validateInfos.currencyType" id="ContractsForm-currencyType" name="currencyType">
                <a-input v-model:value="formModel.currencyType" placeholder="请输入币种" :allow-clear="!disabled"  />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="合同金额" v-bind="validateInfos.amount" id="ContractsForm-amount" name="amount">
                <a-input-number v-model:value="formModel.amount" placeholder="请输入合同金额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="到账总额" v-bind="validateInfos.arriveAmount" id="ContractsForm-arriveAmount" name="arriveAmount">
                <a-input-number v-model:value="formModel.arriveAmount" placeholder="请输入到账总额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="签订日期" v-bind="validateInfos.createTime" id="ContractsForm-createTime" name="createTime">
                <a-date-picker placeholder="请选择签订日期" v-model:value="formModel.createTime" value-format="YYYY-MM-DD" style="width: 100%" allow-clear :suffix-icon="disabled ? null : undefined" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="结束日期" v-bind="validateInfos.endDate" id="ContractsForm-endDate" name="endDate">
                <a-date-picker placeholder="请选择结束日期" v-model:value="formModel.endDate" value-format="YYYY-MM-DD" style="width: 100%" allow-clear :suffix-icon="disabled ? null : undefined" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="开始日期" v-bind="validateInfos.startDate" id="ContractsForm-startDate" name="startDate">
                <a-date-picker placeholder="请选择开始日期" v-model:value="formModel.startDate" value-format="YYYY-MM-DD" style="width: 100%" allow-clear :suffix-icon="disabled ? null : undefined"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="签订人姓名" v-bind="validateInfos.contractSignName" id="ContractsForm-contractSignName" name="contractSignName">
                <a-input v-model:value="formModel.contractSignName" placeholder="请输入签订人姓名" :allow-clear="!disabled" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getContractDetail, getProductTypeList, getProductContentList } from '../Contracts.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
    record: { type: Object, default: () => ({}) },
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formModel = reactive<Record<string, any>>({
    id: '',
    customerId: '',
    contractNumber: '',
    customerName: '',
    contractTheme: '',
    contractCategory: '',
    currencyType: 'RMB',
    amount: undefined,
    arriveAmount: undefined,
    approveName: '',
    createTime: '',
    endDate: '',
    startDate: '',
    productType: '',
    productContent: '',
    contractSignId: '',
    contractSignName: '',
  });


  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });

  // 产品类型和产品内容相关
  const productTypeLoading = ref(false);
  const productContentLoading = ref(false);
  const productTypeOptions = ref<any[]>([]);
  const productContentOptions = ref<any[]>([]);
  const confirmLoading = ref<boolean>(false);
  const validatorRules = reactive({
    // 移除合同编号的必填验证，因为该字段在表单中被隐藏了
    // contractNumber: [
    //   { required: true, message: '合同编号不能为空', trigger: 'blur' },
    // ],
  });
  const { resetFields, validate, validateInfos } = useForm(formModel, validatorRules, { immediate: false });
  const formRef = ref();

  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  function add() {
    nextTick(() => {
      resetFields(); // Reset all fields to their initial state
      // Explicitly clear the ID for a new record
      formModel.id = '';
      // 设置币种默认值
      formModel.currencyType = 'RMB';
      // 加载产品类型列表
      loadProductTypeList();
    });
  }

  async function edit(record) {
    nextTick(async () => {
      resetFields();

      // 先加载产品类型列表
      await loadProductTypeList();

      // 如果有ID，则加载详情（包含文件）
      if (record.id) {
        try {
          const result = await getContractDetail(record.id);
          if (result && result.success) {
            // 设置表单数据
            const contractData = result.result?.contract || record;
            Object.keys(formModel).forEach((key) => {
              if (contractData.hasOwnProperty(key)) {
                formModel[key] = contractData[key];
              }
            });
            
            // 如果币种为空，设置默认值为RMB
            if (!formModel.currencyType) {
              formModel.currencyType = 'RMB';
            }

            // 如果有产品类型，根据产品类型名称找到对应的ID，然后加载产品内容列表
            if (formModel.productType) {
              const selectedProductType = productTypeOptions.value.find(item =>
                (item.productTypeName || item.productType || item.name) === formModel.productType
              );

              if (selectedProductType) {
                await loadProductContentList(selectedProductType.id);
              }
            }

          } else {
            // 如果获取详情失败，则使用传入的记录
            Object.keys(formModel).forEach((key) => {
              if (record.hasOwnProperty(key)) {
                formModel[key] = record[key];
              }
            });
            
            // 如果币种为空，设置默认值为RMB
            if (!formModel.currencyType) {
              formModel.currencyType = 'RMB';
            }
          }
        } catch (error) {
          console.error('加载合同详情失败:', error);
          // 出错时使用传入的记录
          Object.keys(formModel).forEach((key) => {
            if (record.hasOwnProperty(key)) {
              formModel[key] = record[key];
            }
          });
          
          // 如果币种为空，设置默认值为RMB
          if (!formModel.currencyType) {
            formModel.currencyType = 'RMB';
          }
        }
      } else {
        // 没有ID，直接使用传入的记录
        Object.keys(formModel).forEach((key) => {
          if (record.hasOwnProperty(key)) {
            formModel[key] = record[key];
          }
        });
        
        // 如果币种为空，设置默认值为RMB
        if (!formModel.currencyType) {
          formModel.currencyType = 'RMB';
        }
      }
    });
  }

  async function submitForm() {
    try {
      await validate();
    } catch (error: any) {
      if (error?.errorFields) {
        const firstField = error.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(error);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    let model = formModel;
    if (model.id) {
      isUpdate.value = true;
    }
    for (let data in model) {
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    const res = await saveOrUpdate(model, isUpdate.value);
    if (res.success) {
      // If it's a new record and backend returns an ID, update formModel.id
      if (!isUpdate.value && res.result && res.result.id) {
        formModel.id = res.result.id;
      }
      emit('ok'); // Always emit 'ok' on success to close modal and refresh list
    } else {
    }
    confirmLoading.value = false;
  }

  /**
   * 加载产品类型列表
   */
  async function loadProductTypeList() {
    try {
      productTypeLoading.value = true;
      const response = await getProductTypeList();
      console.log('产品类型API响应:', response);

      // 由于HTTP拦截器会在成功时只返回result字段的数据
      // 所以response实际上就是result数组，不是完整的响应对象
      if (response && Array.isArray(response)) {
        productTypeOptions.value = response;
        console.log('产品类型列表:', productTypeOptions.value);
      } else {
        productTypeOptions.value = [];
        console.log('产品类型API返回数据格式异常:', response);
      }
    } catch (error) {
      console.error('获取产品类型列表失败:', error);
      productTypeOptions.value = [];
    } finally {
      productTypeLoading.value = false;
    }
  }

  /**
   * 加载产品内容列表
   */
  async function loadProductContentList(productTypeId) {
    if (!productTypeId) {
      productContentOptions.value = [];
      return;
    }

    try {
      productContentLoading.value = true;
      const response = await getProductContentList(productTypeId);
      console.log('产品内容API响应:', response);

      // 由于HTTP拦截器会在成功时只返回result字段的数据
      // 所以response实际上就是result数组，不是完整的响应对象
      if (response && Array.isArray(response)) {
        productContentOptions.value = response;
        console.log('产品内容列表:', productContentOptions.value);
      } else {
        productContentOptions.value = [];
        console.log('产品内容API返回数据格式异常:', response);
      }
    } catch (error) {
      console.error('获取产品内容列表失败:', error);
      productContentOptions.value = [];
    } finally {
      productContentLoading.value = false;
    }
  }

  /**
   * 产品类型改变事件
   */
  function handleProductTypeChange(value) {
    // 清空产品内容选择
    formModel.productContent = '';

    // 根据产品类型名称找到对应的ID
    const selectedProductType = productTypeOptions.value.find(item =>
      (item.productTypeName || item.productType || item.name) === value
    );

    if (selectedProductType) {
      // 使用产品类型ID加载对应的产品内容列表
      loadProductContentList(selectedProductType.id);
    }
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
  
  .file-upload-section {
    margin-top: 24px;
    padding: 0 14px;
  }
</style>
